#include "Plane.h"
#include <string>

Plane::Plane(std::ifstream& inputFile){
	position[3] = 1.f;
	normalVector[3] = 0.f;
	std::string textureFile;
	
	inputFile >> name >> position[0] >> position[1] >> position[2];
	inputFile >> normalVector[0] >> normalVector[1] >> normalVector[2];
	inputFile >> color.r >> color.g >> color.b;
	inputFile >> ambienceConstant >> diffusionConstant >> specularConstant;
	inputFile >> reflectionConstant >> specularExponent;
	inputFile >> transparency >> refractionIndex;
	inputFile >> textureFile;
	
	if(textureFile.compare("none") != 0)
		texture.readImage(textureFile);
		
	normalVector.normalize();
	distance = position.magnitude();
}

Vector Plane::normal(Vector &surfacePoint){
	return normalVector;
}

std::vector<double> Plane::intersection(Ray& ray){
	std::vector<double> results;

	// Explanation of ray/plane intersection algorithm available here:
	// http://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane_intersection.htm
	double Vd = normalVector.dotProduct(ray.direction);
	if(Vd < -doubleResolution || Vd > doubleResolution){// A solution exists
		double t = -1 * (normalVector.dotProduct(ray.initialPoint) + distance)/Vd;
		if(t > doubleResolution){
			results.push_back(t);
		}
	}
	return results;
}

bool Plane::contains(Vector& point){
	return normalVector.dotProduct(point - position) < -doubleResolution;
}

Color Plane::getColor(Vector& position){
	Color value = color;
	
	if(texture.hasTexture()) {
		// set the axis for the plane
		Vector UAxis = Vector(normalVector[1], normalVector[2], -normalVector[0], normalVector[3]);
		Vector VAxis = UAxis.cross(normalVector);
		
		// find the coordinates on the plane
		// change the numerical scale to make picture smaller
		double u = position.dotProduct(UAxis)/25.0;
		double v = position.dotProduct(VAxis)/25.0;
		value = texture.GetPixel(u,v)*color;
	}
		
	return value;
}
